//
//  BudgetPieVC.m
//  BaseProject
//
//  Created by mac on 2020/10/26.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "BudgetPieVC.h"
#import "BudgetPieTopView.h"
#import "BudgetPieSectionView.h"
#import "BudgetPieCacheModel.h"
@interface BudgetPieVC ()
@property(nonatomic,strong)UIScrollView *mainView;
@property(nonatomic,strong)BudgetPieTopView *topView;
@property(nonatomic,strong)NSMutableArray<BudgetPieItemModel *> *dataSource;
@property(nonatomic,strong)NSMutableArray<BudgetPieSectionView *> *itemsArray;
@property(nonatomic,strong)BudgetPieCacheModel *cacheModel;
//进入控制器时间
@property(nonatomic,strong)NSString *inTime;
@end

@implementation BudgetPieVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createProperty];
    [self createDataSource];
    [self createUI];
    self.inTime = [NSString stringWithFormat:@"%0.0f",[Utilities getCurrentTimestamp]];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self saveBudgetCacheModel];
}
- (void)dealloc
{
    NSLog(@"BudgetPieVC ---dealloc");
    [[StatisticManager shareManager]insertBrowseUserActiveQuantityWithToolType:@"5" WithInTime:self.inTime];
}
- (void)createProperty
{
    NSNumber *number = [[TTUserModel sharedObject].userModelDefault valueForKey:@"buget_totalMoney"];
    self.totalMoney = number.integerValue;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self budgetFilePath];
}
- (void)createDataSource
{
    /**
     1.ff2a2a 2.ff4f4f 3.ff6d6d 4.ffa6a6 5.ffcdcd 6.ff6600 7.ff8400 8.ff9c32 9.ffb96f 10.ffca92 11.ffe1c2
     0.11      0.06     0.03     0.05     0.01     0.015    0.015    0.03     0.03     0.15      0.5
     */
    if (self.cacheModel.dataSource.count > 0) {
        self.dataSource = self.cacheModel.dataSource;
        return;
    }
    [self.dataSource removeAllObjects];
    for (NSInteger index = 0; index < 2; index ++) {
        BudgetPieItemModel *indexModel = [[BudgetPieItemModel alloc]init];
        indexModel.isSelected = YES;
        NSInteger num = 0;
        if (index == 0) {
            indexModel.title = @"婚前消费";
            num = 2;
        } else if (index == 1) {
            indexModel.title = @"婚礼消费";
            num = 9;
        }
        NSMutableArray *array = [NSMutableArray array];
        for (NSInteger flag = 0; flag < num; flag ++) {
            BudgetPieItemModel *flagModel = [[BudgetPieItemModel alloc]init];
            flagModel.isSelected = YES;
            flagModel.imageName = [NSString stringWithFormat:@"budgetPie_%ld_%ld",(long)index,(long)flag];
            if (flag == 0) {
                if (index == 0) {
                    flagModel.title = @"珠宝首饰";
                    flagModel.value = self.totalMoney * 0.11;
                    flagModel.percent = 0.11;
                    flagModel.color = [UIColor colorWithHexString:@"ff2a2a"];
                } else if (index == 1) {
                    flagModel.title = @"请帖喜糖";
                    flagModel.value = self.totalMoney * 0.03;
                    flagModel.percent = 0.03;
                    flagModel.color = [UIColor colorWithHexString:@"ff6d6d"];
                }
            } else if (flag == 1) {
                if (index == 0) {
                    flagModel.title = @"婚纱摄影";
                    flagModel.value = self.totalMoney * 0.06;
                    flagModel.percent = 0.06;
                    flagModel.color = [UIColor colorWithHexString:@"ff4f4f"];
                } else if (index == 1) {
                    flagModel.title = @"婚礼礼服";
                    flagModel.value = self.totalMoney * 0.05;
                    flagModel.percent = 0.05;
                    flagModel.color = [UIColor colorWithHexString:@"ffa6a6"];
                }
            } else if (flag == 2) {
                flagModel.title = @"婚礼跟妆";
                flagModel.value = self.totalMoney * 0.01;
                flagModel.percent = 0.01;
                flagModel.color = [UIColor colorWithHexString:@"ffcdcd"];
            } else if (flag == 3) {
                flagModel.title = @"婚礼摄像";
                flagModel.value = self.totalMoney * 0.015;
                flagModel.percent = 0.015;
                flagModel.color = [UIColor colorWithHexString:@"ff6600"];
            } else if (flag == 4) {
                flagModel.title = @"婚礼摄影";
                flagModel.value = self.totalMoney * 0.015;
                flagModel.percent = 0.015;
                flagModel.color = [UIColor colorWithHexString:@"ff8400"];
            } else if (flag == 5) {
                flagModel.title = @"婚礼司仪";
                flagModel.value = self.totalMoney * 0.03;
                flagModel.percent = 0.03;
                flagModel.color = [UIColor colorWithHexString:@"ff9c32"];
            } else if (flag == 6) {
                flagModel.title = @"婚车租赁";
                flagModel.value = self.totalMoney * 0.03;
                flagModel.percent = 0.03;
                flagModel.color = [UIColor colorWithHexString:@"ffb96f"];
            } else if (flag == 7) {
                flagModel.title = @"婚礼策划";
                flagModel.value = self.totalMoney * 0.15;
                flagModel.percent = 0.15;
                flagModel.color = [UIColor colorWithHexString:@"ffca92"];
            } else if (flag == 8) {
                flagModel.title = @"婚宴酒店";
                flagModel.value = self.totalMoney * 0.5;
                flagModel.percent = 0.5;
                flagModel.color = [UIColor colorWithHexString:@"ffe1c2"];
            }
            [array addObject:flagModel];
        }
        indexModel.dataSource = array;
        [self.dataSource addObject:indexModel];
    }
}
- (void)createUI
{
    self.title = @"婚礼预算表";
    
    [self topView];
    
    WEAKSELF
    CGFloat orinY = self.topView.bottom + 25*ADAPTER_WIDTH;
    for (NSInteger index = 0; index < self.dataSource.count; index ++) {
        BudgetPieSectionView *view = [[BudgetPieSectionView alloc]initWithFrame:CGRectMake(0, orinY, TTScreenWidth, 0)];
        [self.mainView addSubview:view];
        view.iconModel = self.dataSource[index];
        
        orinY = view.bottom + 10*ADAPTER_WIDTH;
        [self.itemsArray addObject:view];
        
        [view setRealTimeCallBackBlock:^{
            [weakSelf handle];
        }];
    }
    self.mainView.contentSize = CGSizeMake(0, orinY + kBottomSafeHeight + 20*ADAPTER_WIDTH);
    
    [self handle];
}
- (void)refreshUI
{
    //刷新sectionUI
    CGFloat orinY = self.topView.bottom + 25*ADAPTER_WIDTH;
    for (NSInteger index = 0; index < self.itemsArray.count; index ++) {
        BudgetPieSectionView *indexView = self.itemsArray[index];
        indexView.iconModel = self.dataSource[index];
        if (indexView.iconModel.isSelected) {
            [self.mainView addSubview:indexView];
            [indexView refreshUI];
            indexView.top = orinY;
            orinY = indexView.bottom + 10*ADAPTER_WIDTH;
        } else {
            [indexView removeFromSuperview];
        }
    }
    self.mainView.contentSize = CGSizeMake(0, MAX(orinY + kBottomSafeHeight + 20*ADAPTER_WIDTH, self.mainView.height + 1));
    //刷新sectionUI
}
- (void)handle
{
    //1.计算总额
    NSInteger totalMoney = 0;
    for (NSInteger index = 0; index < self.dataSource.count; index ++) {
        BudgetPieItemModel *indexModel = self.dataSource[index];
        for (NSInteger flag = 0; flag < indexModel.dataSource.count; flag ++) {
            BudgetPieItemModel *flagModel = indexModel.dataSource[flag];
            if (flagModel.isSelected) {
                totalMoney = totalMoney + flagModel.value;
            }
        }
    }
    //2.重新获取比例
    CGFloat totalPercent = 0.0f;
    for (NSInteger index = 0; index < self.dataSource.count; index ++) {
        BudgetPieItemModel *indexModel = self.dataSource[index];
        for (NSInteger flag = 0; flag < indexModel.dataSource.count; flag ++) {
            BudgetPieItemModel *flagModel = indexModel.dataSource[flag];
            if (flagModel.isSelected) {
                flagModel.percent = ((CGFloat)flagModel.value) / ((CGFloat)totalMoney);
                totalPercent = totalPercent + flagModel.percent;
                NSLog(@"%f %f",flagModel.percent,totalPercent);
            }
        }
    }
    //3.绑定当前数量
    self.totalMoney = totalMoney;
    //4.刷新头部
    self.topView.totalMoney = totalMoney;
    self.topView.dataSource = self.dataSource;
    //5.刷新界面
    [self refreshUI];
    //太过于频繁
    //[self saveBudgetCacheModel];
}
- (void)refreshAll
{
    //重新获取比例
    {
        //1.计算总额
        NSInteger totalMoney = 0;
        for (NSInteger index = 0; index < self.dataSource.count; index ++) {
            BudgetPieItemModel *indexModel = self.dataSource[index];
            for (NSInteger flag = 0; flag < indexModel.dataSource.count; flag ++) {
                BudgetPieItemModel *flagModel = indexModel.dataSource[flag];
                if (flagModel.isSelected) {
                    totalMoney = totalMoney + flagModel.value;
                }
            }
        }
        NSLog(@"totalMoney:%ld",totalMoney);
        //2.获取每一份当前比例 重新配置数量
        CGFloat totalPercent = 0.0f;
        NSInteger newTotalMoney = 0;
        for (NSInteger index = 0; index < self.dataSource.count; index ++) {
            BudgetPieItemModel *indexModel = self.dataSource[index];
            for (NSInteger flag = 0; flag < indexModel.dataSource.count; flag ++) {
                BudgetPieItemModel *flagModel = indexModel.dataSource[flag];
                if (flagModel.isSelected) {
                    CGFloat percent = (CGFloat)flagModel.value / (CGFloat)totalMoney;
                    flagModel.value = (NSInteger)((CGFloat)self.totalMoney * percent);
                    flagModel.percent = percent;
                    /**
                     CGFloat bigPercent = (CGFloat)self.totalMoney / (CGFloat)totalMoney;
                     flagModel.value = (NSInteger)(bigPercent * (CGFloat)flagModel.value);
                     NSLog(@"bigPercent:%f",bigPercent);
                     */
                    totalPercent = percent + totalPercent;
                    newTotalMoney = flagModel.value + newTotalMoney;
                    NSLog(@"percent:%f totalPercent:%f newTotalMoney:%ld",percent,totalPercent,(long)newTotalMoney);
                }
            }
        }
        //3.对最后一个数据内容进行补缺补差
        NSLog(@"self.totalMoney:%ld",self.totalMoney);
        BudgetPieItemModel *lastObj;
        for (NSInteger index = (self.dataSource.count - 1); index >= 0; index --) {
            BudgetPieItemModel *indexModel = self.dataSource[index];
            for (NSInteger flag = (indexModel.dataSource.count - 1); flag >= 0; flag --) {
                BudgetPieItemModel *flagModel = indexModel.dataSource[flag];
                if (flagModel.isSelected && lastObj == nil) {
                    lastObj =  flagModel;
                    break;
                }
            }
        }
        NSLog(@"%ld",lastObj.value);
        if (lastObj) {
            lastObj.value = self.totalMoney - (newTotalMoney - lastObj.value);
        }
        NSLog(@"%ld",lastObj.value);
    }
    //刷新UI数据准备
    NSInteger totalMoney = 0;
    for (NSInteger index = 0; index < self.dataSource.count; index ++) {
        BudgetPieItemModel *indexModel = self.dataSource[index];
        NSInteger indexNum = 0;
        for (NSInteger flag = 0; flag < indexModel.dataSource.count; flag ++) {
            BudgetPieItemModel *flagModel = indexModel.dataSource[flag];
            if (flagModel.isSelected) {
                totalMoney = totalMoney + flagModel.value;
                indexNum = indexNum + 1;
            }
        }
        if (indexNum == 0) {
            indexModel.isSelected = NO;
        } else {
            indexModel.isSelected = YES;
        }
    }
    //刷新头部
    self.topView.totalMoney = totalMoney;
    self.topView.dataSource = self.dataSource;
    //刷新头部
    //刷新sectionUI
    [self refreshUI];
    //刷新sectionUI
    
    [self saveBudgetCacheModel];
}
- (void)changeTotalMoney:(NSInteger)totalMoney
{
    self.totalMoney = totalMoney;
    self.cacheModel.dataSource = [NSMutableArray array];
    [self createDataSource];
    //4.刷新头部
    self.topView.totalMoney = totalMoney;
    self.topView.dataSource = self.dataSource;
    //5.刷新界面
    [self refreshUI];
    
    [self saveBudgetCacheModel];
    return;
    //2.绑定当前数量
    self.totalMoney = totalMoney;
    //1.重新获取每份数量
    NSInteger newTotalMoney = 0;
    for (NSInteger index = 0; index < self.dataSource.count; index ++) {
        BudgetPieItemModel *indexModel = self.dataSource[index];
        for (NSInteger flag = 0; flag < indexModel.dataSource.count; flag ++) {
            BudgetPieItemModel *flagModel = indexModel.dataSource[flag];
            if (flagModel.isSelected) {
                flagModel.value = (NSInteger)((CGFloat)totalMoney * flagModel.percent);
                newTotalMoney = newTotalMoney + flagModel.value;
                NSLog(@"%ld %ld",(long)flagModel.value,(long)newTotalMoney);
            }
        }
    }
    //2.对最后一个数据内容进行补缺补差
    NSLog(@"self.totalMoney:%ld",self.totalMoney);
    BudgetPieItemModel *lastObj;
    for (NSInteger index = (self.dataSource.count - 1); index >= 0; index --) {
        BudgetPieItemModel *indexModel = self.dataSource[index];
        for (NSInteger flag = (indexModel.dataSource.count - 1); flag >= 0; flag --) {
            BudgetPieItemModel *flagModel = indexModel.dataSource[flag];
            if (flagModel.isSelected && lastObj == nil) {
                lastObj =  flagModel;
                break;
            }
        }
    }
    NSLog(@"%ld",lastObj.value);
    if (lastObj) {
        lastObj.value = self.totalMoney - (newTotalMoney - lastObj.value);
    }
    NSLog(@"%ld",lastObj.value);
    
    //4.刷新头部
    self.topView.totalMoney = totalMoney;
    self.topView.dataSource = self.dataSource;
    //5.刷新界面
    [self refreshUI];
    
    [self saveBudgetCacheModel];
}
#pragma mark - lazy懒加载
- (UIScrollView *)mainView
{
    if (!_mainView) {
        UIScrollView *view = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, TTScreenWidth, TTScreenHeight - kNavBarAndStatusBarHeight)];
        [self.view addSubview:view];
        view.backgroundColor = RGB(255, 219, 219);
        view.showsVerticalScrollIndicator = NO;
        _mainView = view;
    }
    return _mainView;
}
- (BudgetPieTopView *)topView
{
    if (!_topView) {
        BudgetPieTopView *view = [[BudgetPieTopView alloc]initWithFrame:CGRectMake(16*ADAPTER_WIDTH, 23*ADAPTER_WIDTH, TTScreenWidth - 32*ADAPTER_WIDTH, 380*ADAPTER_WIDTH)];
        [self.mainView addSubview:view];
        view.parentVC = self;
        WEAKSELF
        [view setRefreshBlock:^{
            [weakSelf refreshAll];
        }];
        [view setCallBackTotalMoney:^(NSInteger totalMoney) {
            [weakSelf changeTotalMoney:totalMoney];
        }];
        _topView = view;
    }
    return _topView;
}
- (NSMutableArray<BudgetPieSectionView *> *)itemsArray
{
    if (!_itemsArray) {
        _itemsArray = [NSMutableArray array];
    }
    return _itemsArray;
}
- (NSMutableArray<BudgetPieItemModel *> *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
#pragma mark - 缓存模块
- (NSString *)budgetFilePath
{
    NSString *filePath = [self currentDirAppendDir:[self getDocumentDirectory] appendDir:@"budget_data"];
    filePath = [filePath stringByAppendingPathComponent:@"account.plist"];
    NSLog(@"%@",filePath);
    return filePath;
}
- (NSString *)getDocumentDirectory
{
    NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [directories firstObject];
}
- (NSString *)currentDirAppendDir:(NSString *)currentDir appendDir:(NSString *)appendDir
{
    NSString *pathDir = [currentDir stringByAppendingPathComponent:appendDir];
    if (![[NSFileManager defaultManager] fileExistsAtPath:pathDir])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:pathDir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return pathDir;
}
- (BudgetPieCacheModel *)cacheModel
{
    if (!_cacheModel) {
        if ([[NSFileManager defaultManager]fileExistsAtPath:[self budgetFilePath]]) {
            _cacheModel = [NSKeyedUnarchiver unarchiveObjectWithFile:[self budgetFilePath]];
        } else {
            _cacheModel = [[BudgetPieCacheModel alloc]init];
        }
    }
    return _cacheModel;
}
- (BOOL)saveBudgetCacheModel
{
    if (self.cacheModel == nil) {
        return NO;
    }
    self.cacheModel.totalMoney = self.totalMoney;
    self.cacheModel.dataSource = self.dataSource;
    return [NSKeyedArchiver archiveRootObject:self.cacheModel toFile:[self budgetFilePath]];
}
@end
